package com.tako.utils;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;

/**
 * @author zhangyu
 * @date 2023/1/17
 */
public class PDFUtil {


    public static void mergeFiles(String inputFolderPath, String outputPath) throws IOException, DocumentException {
        File inputFolderFile = Paths.get(inputFolderPath).toFile();
        File[] inputFiles = inputFolderFile.listFiles();

        FileOutputStream out = new FileOutputStream(outputPath);

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, out);
        document.open();

        if (inputFiles == null) return;
        for (File inputFile : inputFiles) {
            if (inputFile.isDirectory()) {
                // 跳过文件夹
                continue;
            }
            String[] fileNamePart = FileUtil.getFileNamePart(inputFile);
            String ext = fileNamePart[1].toLowerCase();
            switch (ext) {
                case "jpg":
                case "jpeg":
                case "png":
                    appendImg(document, inputFile.getPath());
                    break;
                case "pdf":
                    appendPdf(document, inputFile.getPath(), writer);
                    break;
                default:
                    break;
            }

        }
        out.flush();
        document.close();
        out.close();
    }

    private static void appendImg(Document document, String imagePath) throws IOException, DocumentException {
        document.newPage();
        Image img = Image.getInstance(imagePath);
        img.setAlignment(Image.MIDDLE);
        img.setBorder(Image.BOX);
        img.setBorderWidth(10);
        img.setBorderColor(BaseColor.WHITE);
        img.scaleToFit(document.getPageSize());
        document.add(img);
    }

    private static void appendPdf(Document document, String pdfPath, PdfWriter writer) throws DocumentException, IOException {
        PdfContentByte cb = writer.getDirectContent();
        PdfReader pdfReader = new PdfReader(pdfPath);
        int numberOfPages = pdfReader.getNumberOfPages();
        for (int i = 1; i <= numberOfPages; i++) {
            document.newPage();
            PdfImportedPage page = writer.getImportedPage(pdfReader, i);
            cb.addTemplate(page, 0, 0);
        }
    }
}
